package com.wangzhen.spring.ioc.lifecycle.beandefinition;

import com.wangzhen.spring.ioc.dependcy.entity.User;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;

/**
 * 演示：基于Properties文件的bean定义
 */
public class PropertiesMetadataConfigurationDemo {

    public static void main(String[] args) {
        // 实例bean工厂
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
        // 实例化基于properties文件的 BeanDefinitionReader
        PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(factory);
        // 读取properties文件是默认按照ISO-8859-1的方式，也就是ASCII码方式
        // 存在乱码的可能
        String location = "classpath:/META-INF/user.properties";
//        int beanDefinition = reader.loadBeanDefinitions(location);
//        System.out.println("加载的bean定义数量为："+ beanDefinition);

        // spring 提供了另外一种可以指定编码的方式来读取配置文件,用来解决读取配置文件乱码的问题
        Resource resource = new ClassPathResource("/META-INF/user.properties");
        EncodedResource encodedResource = new EncodedResource(resource, "UTF-8");
        int beanDefinition = reader.loadBeanDefinitions(encodedResource);
        System.out.println("加载的bean定义数量为："+ beanDefinition);


        User user = factory.getBean(User.class);
        System.out.println(user);
    }
}
